﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CIT.WMS.Product.Bll;

namespace CIT.WMS.Product
{
    public partial class FrmProductOutByCustomer : Form
    {
        public FrmProductOutByCustomer()
        {
            InitializeComponent();
        }
        DataTable DtOut;
        DataTable _RecomDt;

        string realLocationSN;
        string recomLocationSN;
        string recomPartNumber;
        string realPartNumber;

        int maxQty;

        string _BillType = "";
        string _Customer = "";

        bool isInStockBillNo = false;
        List<BoxInfo> outBoxList;

        private void cmb_Doc_SelectedIndexChanged(object sender, EventArgs e)
        {
            InputBillNo();
        }

        public void InputBillNo()
        {
            DtOut = Bll_ProductOut.GetOutStockLists(cmb_Doc.Text);
            DataRow[] drOut = DtOut.Select(string.Format(" BillNo = '{0}'", cmb_Doc.Text));
            if (drOut.Length > 0)
            {
                var billNo = cmb_Doc.Text;
                DataTable info = Bll_ProductOut.GetOutStockInfo(cmb_Doc.Text);
                _BillType = info.Rows[0]["BillType"].ToString();
                //苹果C6305/C6242/C6883
                _Customer = info.Rows[0]["CustomerSN"].ToString();

                if (info.Rows.Count > 0)
                {
                    if (string.IsNullOrEmpty(info.Rows[0]["Updator"].ToString()) || Utils.uContext.UserNamek__BackingField.Equals(info.Rows[0]["Updator"].ToString()))
                    {
                        lab_StorageSN.Text = info.Rows[0]["Storage_SN"].ToString();
                        if (_BillType.Contains("返工"))
                        {
                            lab_msg.Text = cmb_Doc.Text + "订单类型错误,请输入正确的单据!";
                            cmb_Doc.Focus();
                            cmb_Doc.Text = "";
                            lab_StorageSN.Text = "";
                        }
                        else
                        {
                            //2023-06-23ADD***物料FATP判断
                            var rowType = Bll_ProductOut.GetDeliveryInfo(billNo);
                            var outType = Bll_ProductIn.GetFatp(rowType.Rows[0]["ProductNumber"].ToString());
                            _RecomDt = Utils.NMS.sqlDBService.GetSuggestSN(lab_StorageSN.Text, cmb_Doc.Text);
                            if (string.IsNullOrEmpty(outType))
                                _RecomDt = Utils.NMS.sqlDBService.GetRecommendLocationSN(Utils.uContext.CompanyNamek__BackingField, lab_StorageSN.Text, cmb_Doc.Text);
                        }

                        var recRes = GetRecommend();
                        var IsEnd = false;
                        lab_msg.Text = "当前料号:" + recomPartNumber + "\r\n" + GetBillInfoMsg(billNo, out IsEnd);

                        if (!recRes && !IsEnd)
                        {
                            MessageBox.Show("库存不足，" + cmb_Doc.Text + "无法推荐库位！");
                            cmb_Doc.Focus();
                            cmb_Doc.Text = "";
                            lab_Recom.Text = "";
                            txt_BoxNo.Text = "";
                            txt_LocationSN.Text = "";
                            txt_Qty.Text = "";
                        }
                    }
                    else
                    {
                        MessageBox.Show(cmb_Doc.Text + "已被" + info.Rows[0]["Updator"].ToString() + "操作，请选择其他单号!");
                        lab_StorageSN.Text = "";
                        cmb_Doc.Text = "";
                        cmb_Doc.Focus();
                    }
                }
            }
            else
            {
                lab_msg.Text = cmb_Doc.Text + "单号不正确,请输入正确的单据!";
                cmb_Doc.Focus();
                cmb_Doc.Text = "";
                lab_StorageSN.Text = "";
            }
        }

        public string GetBillInfoMsg(string billNo, out bool IsEnd)
        {
            var dt = Bll_ProductOut.GetDeliveryInfo(billNo);
            var boxCount = Bll_ProductOut.GetOutStockBoxsCount(billNo);

            var result = string.Empty;
            IsEnd = false;
            if (dt.Rows.Count > 0)
            {
                StringBuilder sb = new StringBuilder();

                sb.AppendLine("已扫描箱数:" + boxCount);
                var isFinish = true;
                foreach (DataRow dr in dt.Rows)
                {
                    var planQty = 0;
                    if (!string.IsNullOrEmpty(dr["PlanQty"].ToString()))
                    {
                        planQty = Convert.ToInt32(dr["PlanQty"]);
                    }
                    var realQty = 0;
                    if (!string.IsNullOrEmpty(dr["SelectQty"].ToString()))
                    {
                        realQty = Convert.ToInt32(dr["SelectQty"]);
                    }
                    sb.AppendLine("物料号:" + dr["ProductNumber"] + ";数量:" + realQty + "/" + planQty);

                    if (planQty > realQty)
                    {
                        isFinish = false;
                    }
                }
                result = sb.ToString();
                if (isFinish)
                {
                    IsEnd = true;
                    //MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
                    //DialogResult dr = MessageBox.Show("出库单:" + billNo + "出库数量已经等于计划数量，是否确认完成?", "是否完成", messButton, MessageBoxIcon.None, MessageBoxDefaultButton.Button1);
                    MessageBox.Show("出库单:" + billNo + "出库数量已经等于计划数量");
                    //if (dr == DialogResult.OK)
                    {
                        lab_StorageSN.Text = "";
                        cmb_Doc.Focus();
                        cmb_Doc.Text = "";
                        txt_BoxNo.Text = "";
                        txt_LocationSN.Text = "";
                        txt_Qty.Text = "";
                    }
                }
            }
            return result;
        }

        public bool GetRecommend()
        {
            var result = false;
            if (_RecomDt != null && _RecomDt.Rows.Count > 0)
            {
                var dr = _RecomDt.Rows[0];
                recomLocationSN = dr["Location_SN"].ToString();
                recomPartNumber = dr["PartNumber"].ToString();
                try
                {
                    lab_Recom.Text = recomLocationSN.Split('#')[1] + recomLocationSN.Split('#')[2] + ":" + dr["Qty"].ToString() + " " + dr["Version"].ToString();
                }
                catch (Exception ex)
                {
                    lab_Recom.Text = dr["Storage_SN"].ToString();
                }

                txt_BoxNo.Focus();
                txt_BoxNo.Text = "";
                txt_Qty.Text = "";

                // 20210517 追加开始
                txt_Qty.ReadOnly = false;
                outBoxList = null;
                isInStockBillNo = false;
                // 20210517 追加结束
                result = true;
            }
            else
            {
                recomLocationSN = string.Empty;
                recomPartNumber = string.Empty;

                cmb_Doc.Focus();
                cmb_Doc.Text = "";
                lab_Recom.Text = "";
                txt_BoxNo.Text = "";
                txt_LocationSN.Text = "";
                txt_Qty.Text = "";

                // 20210517 追加开始
                txt_Qty.ReadOnly = false;
                outBoxList = null;
                isInStockBillNo = false;
                // 20210517 追加结束
            }

            return result;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (cmb_Doc.Text == null || cmb_Doc.Text.ToString() == "")
            {
                //lab_msg.Text = "请先选择单据";
                MessageBox.Show("请先选择单据");
                return;
            }

            _RecomDt = Utils.NMS.sqlDBService.GetSuggestSN(lab_StorageSN.Text, cmb_Doc.Text);
            var outType = Bll_ProductIn.GetFatp(realPartNumber);
            if (string.IsNullOrEmpty(outType))
                _RecomDt = Utils.NMS.sqlDBService.GetRecommendLocationSN(Utils.uContext.CompanyNamek__BackingField, lab_StorageSN.Text, cmb_Doc.Text);

            if (!(_RecomDt != null && _RecomDt.Rows.Count > 0))
            {
                MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
                DialogResult dr = MessageBox.Show("库存不足，" + cmb_Doc.Text + "无法推荐库位！是否强制出库??", "出库确认", messButton, MessageBoxIcon.None, MessageBoxDefaultButton.Button1);

                if (dr == DialogResult.OK)
                {
                    _RecomDt = Bll_ProductOut.GetRecommendLocationSNQC(Utils.uContext.CompanyNamek__BackingField, lab_StorageSN.Text, cmb_Doc.Text);
                }
            }

            GetRecommend();

            var IsEnd = false;
            lab_msg.Text = GetBillInfoMsg(cmb_Doc.Text, out IsEnd);
        }

        private void txt_BoxNo_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != 13)
            {
                return;
            }
            if (string.IsNullOrEmpty(cmb_Doc.Text))
            {
                MessageBox.Show("请选择单号!");
                cmb_Doc.Focus();
                return;
            }
            if (string.IsNullOrEmpty(txt_BoxNo.Text))
            {
                MessageBox.Show("箱号不能为空!");
                return;
            }
            if (_RecomDt.Rows.Count == 0)
            {
                MessageBox.Show("库存不足，" + cmb_Doc.Text + "无法推荐库位！");
                return;
            }

            // 20210517 追加开始
            isInStockBillNo = false;
            DataTable dt = Bll_ProductOut.GetBoxNoList(txt_BoxNo.Text);
            if (dt.Rows.Count > 0)
            {
                if ("1".Equals(dt.Rows[0]["OutStatus"]))
                {
                    MessageBox.Show("该入库单号:" + txt_BoxNo.Text + "已扫描！");
                    txt_BoxNo.Text = "";
                    return;
                }
                realPartNumber = _RecomDt.Rows[0]["PartNumber"].ToString();
                if (!string.Equals(realPartNumber, dt.Rows[0]["PartNumber"]))
                {
                    MessageBox.Show("该入库单号:" + txt_BoxNo.Text + "物料号不对！");
                    txt_BoxNo.Text = "";
                    return;
                }

                // 入库单详细
                FrmInStockDetails f = new FrmInStockDetails();
                f.InStockBillNo = txt_BoxNo.Text;
                f.OutStockBillNo = cmb_Doc.Text;
                f.OutStockBillType = this._BillType;
                f.BoxNoList = dt;
                f.ShowDialog();
                this.outBoxList = f.OutBoxList;
                if (this.outBoxList != null && this.outBoxList.Count > 0)
                {
                    isInStockBillNo = true;
                    this.txt_Qty.Text = this.outBoxList.Select(x => Decimal.Parse(x.Qty)).Sum().ToString();
                    this.txt_Qty.ReadOnly = true;
                    this.txt_LocationSN.Focus();
                }
                else
                {
                    this.txt_BoxNo.Text = "";
                    this.txt_Qty.Text = "";
                    this.txt_Qty.ReadOnly = false;
                    this.txt_BoxNo.Focus();
                }
                return;
            }
            else
            {
                this.txt_Qty.ReadOnly = false;
            }

            //20211018 追加8码支持
            bool is8Code = false;
            var CodeArray = txt_BoxNo.Text.Split(',');
            if (CodeArray != null && CodeArray.Length == 8)
            {
                var n1 = CodeArray[0];
                if (n1.Length != 1)
                {
                    MessageBox.Show("8码第1位长度只能为1");
                    txt_BoxNo.Text = "";
                    txt_BoxNo.Focus();
                    return;
                }

                string partNumber = CodeArray[2];
                realPartNumber = _RecomDt.Rows[0]["PartNumber"].ToString();
                if (partNumber.Trim().Contains(realPartNumber.Trim()) == false)
                {
                    MessageBox.Show("条码中的物料号与所需物料不匹配");
                    txt_BoxNo.Text = "";
                    txt_BoxNo.Focus();
                    return;
                }

                txt_Qty.Text = CodeArray[5];
                is8Code = true;
            }

            // 20210517 追加结束
            var splitList = txt_BoxNo.Text.Split('-');
            var boxNo = splitList.FirstOrDefault();
            if (is8Code == false)
            {
                txt_BoxNo.Text = boxNo;
            }

            if ("C6305/C6242/C6883".Contains(_Customer) && _Customer.Equals("") == false)
            {
                var isReg = false;
                if (txt_BoxNo.Text.StartsWith("GTT") || txt_BoxNo.Text.StartsWith("CYV"))
                {
                    if (txt_BoxNo.Text.Length == 17)
                    {
                        isReg = true;
                    }
                }

                if (isReg == false)
                {
                    txt_BoxNo.Text = "";
                    txt_BoxNo.Focus();
                    MessageBox.Show("箱号规则不正确，请扫描正确的箱号。");
                    return;
                }
            }

            DataTable dateHoldBox = Bll_ProductOut.GetHoldBox(txt_BoxNo.Text);
            if (dateHoldBox != null && dateHoldBox.Rows.Count > 0)
            {
                MessageBox.Show("该箱号:" + txt_BoxNo.Text + "已冻结，不能出库！");
                return;
            }

            var isExit = Bll_ProductOut.IsExitBill(cmb_Doc.Text, txt_BoxNo.Text);
            if (isExit)
            {
                MessageBox.Show(txt_BoxNo.Text + "已扫描!");
                txt_BoxNo.Text = "";
                return;
            }

            if (is8Code == false)
            {
                DataTable dtBox = Bll_ProductOut.GetBoxNoInfo(txt_BoxNo.Text);

                realPartNumber = _RecomDt.Rows[0]["PartNumber"].ToString();

                if (dtBox == null || dtBox.Rows.Count == 0)
                {
                    if (splitList.Count() > 1)
                    {
                        try
                        {
                            maxQty = Convert.ToInt32(splitList.LastOrDefault());
                        }
                        catch
                        {
                            maxQty = 0;
                        }
                    }
                    else
                    {
                        maxQty = 0;
                    }
                    MessageBox.Show("系统无" + txt_BoxNo.Text + "箱号信息，请确认此箱物料号与出库单中物料号一致！");
                }
                else
                {
                    var realQty_Box = 0;

                    if (!string.IsNullOrEmpty(dtBox.Rows[0]["RealQty"].ToString()))
                    {
                        realQty_Box = Convert.ToInt32(dtBox.Rows[0]["RealQty"]);
                    }

                    if (dtBox.Rows[0]["Status"].ToString().Equals("1") || realQty_Box == 0)
                    {
                        MessageBox.Show(txt_BoxNo.Text + "已被使用，请选择其他箱！");
                        return;
                    }

                    maxQty = realQty_Box;

                    if (!realPartNumber.Equals(dtBox.Rows[0]["PartNumber"].ToString()))
                    {
                        MessageBox.Show(txt_BoxNo.Text + "箱号物料号不对，请重新扫描！");
                        txt_BoxNo.Text = "";
                        txt_BoxNo.Focus();
                        return;
                    }
                }

                if (maxQty == 0)
                {
                    txt_Qty.Text = string.Empty;
                }
                else
                {
                    txt_Qty.Text = maxQty.ToString();
                }
            }
            txt_Qty.Focus();

        }

        public bool CheckBillNoProNumIsFinish(string billNo, string productNumber, int qty, out int diff)
        {
            var dt = Bll_ProductOut.GetDeliveryInfo(billNo);

            var isFinish = true;
            diff = 0;
            foreach (DataRow dr in dt.Rows)
            {
                if (productNumber.Equals(dr["ProductNumber"].ToString()))
                {
                    var planQty = 0;
                    if (!string.IsNullOrEmpty(dr["PlanQty"].ToString()))
                    {
                        planQty = Convert.ToInt32(dr["PlanQty"]);
                    }
                    var realQty = 0;
                    if (!string.IsNullOrEmpty(dr["SelectQty"].ToString()))
                    {
                        realQty = Convert.ToInt32(dr["SelectQty"]);
                    }
                    diff = planQty - realQty;
                    realQty = realQty + qty;
                    if (planQty > realQty)
                    {
                        isFinish = false;
                    }
                    break;
                }

            }
            return isFinish;
        }

        private void cmb_Doc_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                InputBillNo();
            }
        }

        private void txt_LocationSN_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != 13)
            {
                return;
            }
            if (string.IsNullOrEmpty(txt_BoxNo.Text))
            {
                MessageBox.Show("箱号不能为空!");
                return;
            }

            // 20210517 追加开始
            if (isInStockBillNo)
            {
                doProductOutStock();
                return;
            }
            // 20210517 追加结束

            var splitList = txt_BoxNo.Text.Split('-');
            var boxNo = splitList.FirstOrDefault();
            txt_BoxNo.Text = boxNo;

            if (_BillType.Contains("返工出库单") == false)
            {
                DataTable dateHoldBox = Bll_ProductOut.GetHoldBox(txt_BoxNo.Text);
                if (dateHoldBox != null && dateHoldBox.Rows.Count > 0)
                {
                    MessageBox.Show("该箱号:" + txt_BoxNo.Text + "已冻结，不能出库！");
                    return;
                }
            }

            var isExit = Bll_ProductOut.IsExitBill(cmb_Doc.Text, txt_BoxNo.Text);
            if (isExit)
            {
                MessageBox.Show(txt_BoxNo.Text + "已扫描!");
                return;
            }


            if (string.IsNullOrEmpty(txt_Qty.Text))
            {
                //lab_msg.Text = "请输入出库成品数量!";
                MessageBox.Show("请输入出库成品数量!");
                return;
            }

            var boxnumDt = Bll_ProductOut.GetBoxNum(txt_BoxNo.Text);

            var BoolBN = false;

            if (boxnumDt != null && boxnumDt.Rows.Count > 0)
            {
                var PutawayQty = Convert.ToInt32(boxnumDt.Rows[0]["PutawayQty"]);
                if (PutawayQty < Convert.ToInt32(Convert.ToDecimal(txt_Qty.Text)))
                {
                    BoolBN = true;
                }
            }
            if (BoolBN)
            {
                MessageBox.Show("该箱号" + txt_BoxNo.Text + "输入的数量超过实际的数量！");
                return;
            }

            if (string.IsNullOrEmpty(realPartNumber))
            {
                MessageBox.Show("请先输入箱号并回车！");
                txt_BoxNo.Focus();
                return;
            }

            if (txt_LocationSN.Text.Contains("#"))
            {
                realLocationSN = txt_LocationSN.Text;
            }

            if (realLocationSN == null)
            {
                realLocationSN = "";
            }

            var arry = realLocationSN.Split('#');
            if (arry.Count() < 3)
            {
                MessageBox.Show("输入的库位格式不正确，请重新输入！");
                txt_LocationSN.Text = "";
                txt_LocationSN.Focus();
                return;
            }
            txt_LocationSN.Text = arry[1] + arry[2];

            var status = Bll_ProductOut.GetLocationSNStatusInInventory(realLocationSN);
            if (status == 0)
            {
                var str = txt_LocationSN.Text + "库存不足，请点击重新推荐按钮，选择其他推荐库位！";

                MessageBox.Show(str);
                txt_LocationSN.Text = "";
                txt_LocationSN.Focus();
                return;
            }

            var qty = Convert.ToInt32(Convert.ToDecimal(txt_Qty.Text));
            var locationSNQty = Convert.ToInt32(_RecomDt.Rows[0]["Qty"]);
            if (qty == 0)
            {
                MessageBox.Show("出库成品数不能为0或者为空!");
                return;
            }

            string version = string.Empty;
            if (_BillType.Contains("返工出库单") == false)
            {
                //2023-06-23ADD***物料FATP判断
                var outType = Bll_ProductIn.GetFatp(realPartNumber);

                var dtInver = Bll_ProductIn.GetInventoryInfo(realLocationSN, realPartNumber);
                string extInver = string.Empty;
                if (dtInver != null && dtInver.Rows.Count > 0)
                {
                    extInver = dtInver.Rows[0]["Ext1"].ToString();
                    version = dtInver.Rows[0]["Version"].ToString();
                }
                bool isPD = false;
                if (string.IsNullOrEmpty(extInver) || extInver.Length != 8)
                {
                    isPD = true;
                }
                else
                {
                    try
                    {
                        DateTime ditetimeExt = Convert.ToDateTime(extInver.Substring(0, 4) + "-" + extInver.Substring(4, 2) + "-" + extInver.Substring(6, 2));
                        if (outType.Equals("FATP"))
                        {
                            if (ditetimeExt >= Utils.GetSysDate().AddDays(-60))
                            {
                                MessageBox.Show("扩展有效期天数小于等于60天，不允许出货，请找OQC确认");
                                return;
                            }
                        }
                        else if (outType.Equals("Flex etc"))
                        {
                            if (ditetimeExt >= Utils.GetSysDate().AddDays(-30))
                            {
                                MessageBox.Show("扩展有效期天数小于等于30天，不允许出货，请找OQC确认");
                                return;
                            }
                        }
                        else
                        {
                            if (ditetimeExt >= Utils.GetSysDate())
                            {
                                isPD = false;
                            }
                        }
                    }
                    catch
                    {
                        MessageBox.Show("该库位有效期不是正确的日期格式!");
                        return;
                    }
                }
                //没有扩展有效期
                if (isPD)
                {
                    var dtLiftTime = Bll_ProductOut.GetExpriTime(realPartNumber, realLocationSN);
                    if (dtLiftTime.Rows.Count > 0)
                    {
                        var lifeTime = Convert.ToInt16(dtLiftTime.Rows[0]["ShelfLifeTime"].ToString());
                        var diff = Convert.ToInt16(dtLiftTime.Rows[0]["Diff"].ToString());

                        if (outType.Equals("FATP"))
                        {
                            if (diff <= 60)
                            {
                                MessageBox.Show("管控有效期天数小于等于60天，不允许出货，请找OQC确认");
                                return;
                            }
                        }
                        else if (outType.Equals("Flex etc"))
                        {
                            if (diff <= 60)
                            {
                                MessageBox.Show("管控有效期天数小于等于30天，不允许出货，请找OQC确认");
                                return;
                            }
                        }
                        else
                        {
                            if (lifeTime <= 30 && diff <= 7)
                            {
                                MessageBox.Show("有效期不足7天，无法出库!!");
                                return;
                            }

                            if (lifeTime > 30 && diff <= 30)
                            {
                                MessageBox.Show("有效期不足30天，无法出库!!");
                                return;
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("该物料有效期已过，无法出库!!");
                        return;
                    }
                }
            }

            var isCanAddQty = Bll_ProductOut.OutStockIsCanAddQty(cmb_Doc.Text, realPartNumber, qty);
            if (!isCanAddQty)
            {
                MessageBox.Show("物料号" + realPartNumber + "的出库数量" + qty + "不能大于计划数量!");
                txt_Qty.Text = "";
                return;
            }

            //bool isTrue = Bll_ProductOut.ProductOutStock(cmb_Doc.Text, txt_BoxNo.Text, qty, realLocationSN, realPartNumber);
            bool isTrue = Utils.NMS.sqlDBService.ProductOutStock(cmb_Doc.Text, txt_BoxNo.Text, qty, realLocationSN, realPartNumber, Utils.uContext.UserNamek__BackingField);
            if (isTrue)
            {
                //_RecomDt = Bll_ProductOut.GetRecommendLocationSN(Utils.uContext.CompanyNamek__BackingField, lab_StorageSN.Text, cmb_Doc.Text);
                _RecomDt = Utils.NMS.sqlDBService.GetSuggestSN(lab_StorageSN.Text, cmb_Doc.Text);
                var Isend = false;
                lab_msg.Text = txt_BoxNo.Text + "出库成功！\r\n" + "当前料号:" + recomPartNumber + " " + version + "\r\n" + GetBillInfoMsg(cmb_Doc.Text, out Isend);
                //MessageBox.Show(txt_BoxNo.Text + "出库成功！/n" + GetBillInfoMsg(cmb_Doc.Text));
                GetRecommend();

            }
            else
            {
                MessageBox.Show(txt_BoxNo.Text + "出库失败，请检查箱号与库位是否一致,或此库位是否有足够的成品！");
                txt_BoxNo.Focus();
                txt_BoxNo.Text = "";
                txt_Qty.Text = "";
                txt_LocationSN.Text = "";
            }

        }

        private void txt_Qty_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != 13)
            {
                return;
            }

            if (string.IsNullOrEmpty(txt_BoxNo.Text))
            {
                MessageBox.Show("箱号不能为空!");
                return;
            }

            if (string.IsNullOrEmpty(txt_Qty.Text))
            {
                MessageBox.Show("请输入出库成品数量!");
                return;
            }

            if (string.IsNullOrEmpty(realPartNumber))
            {
                MessageBox.Show("请先输入箱号并回车！");
                txt_BoxNo.Focus();
                return;
            }

            txt_Qty.Text = txt_Qty.Text.Split('-').LastOrDefault();

            var qty = 0;

            try
            {
                qty = Convert.ToInt32(Convert.ToDecimal(txt_Qty.Text));
            }
            catch (Exception ex)
            {
                MessageBox.Show("只能输入数字!");
                txt_Qty.Text = "";
                return;
            }

            var locationSNQty = Convert.ToInt32(_RecomDt.Rows[0]["Qty"]);
            if (qty == 0)
            {
                MessageBox.Show("出库成品数量不能为0或者为空!");
                return;
            }

            txt_LocationSN.Focus();
        }

        /// <summary>
        /// 出库（入库单单位）
        /// </summary>
        private void doProductOutStock()
        {
            if (string.IsNullOrEmpty(realPartNumber))
            {
                MessageBox.Show("请先输入箱号并回车！");
                txt_BoxNo.Focus();
                return;
            }

            if (string.IsNullOrEmpty(txt_Qty.Text))
            {
                MessageBox.Show("请输入出库成品数量!");
                //txt_Qty.Focus();
                return;
            }

            if (txt_LocationSN.Text.Contains("#"))
            {
                realLocationSN = txt_LocationSN.Text;
            }

            if (realLocationSN == null)
            {
                realLocationSN = "";
            }

            var arry = realLocationSN.Split('#');
            if (arry.Count() < 3)
            {
                MessageBox.Show("输入的库位格式不正确，请重新输入！");
                txt_LocationSN.Text = "";
                txt_LocationSN.Focus();
                return;
            }
            txt_LocationSN.Text = arry[1] + arry[2];

            var status = Bll_ProductOut.GetLocationSNStatusInInventory(realLocationSN);
            if (status == 0)
            {
                var str = txt_LocationSN.Text + "库存不足，请点击重新推荐按钮，选择其他推荐库位！";
                MessageBox.Show(str);
                txt_LocationSN.Text = "";
                txt_LocationSN.Focus();
                return;
            }
            if (status == -1 && _BillType.Contains("返工") == false)
            {
                var str = txt_LocationSN.Text + "库位已经被HOLD，无法出库";
                MessageBox.Show(str);
                txt_LocationSN.Text = "";
                txt_LocationSN.Focus();
                return;
            }

            var qty = Convert.ToInt32(Convert.ToDecimal(txt_Qty.Text));
            if (qty == 0)
            {
                MessageBox.Show("出库成品数不能为0或者为空!");
                return;
            }

            string version = string.Empty;
            if (_BillType.Contains("返工出库单") == false)
            {
                //2023-06-23ADD***物料FATP判断
                var outType = Bll_ProductIn.GetFatp(realPartNumber);

                var dtInver = Bll_ProductIn.GetInventoryInfo(realLocationSN, realPartNumber);
                string extInver = string.Empty;

                if (dtInver != null && dtInver.Rows.Count > 0)
                {
                    extInver = dtInver.Rows[0]["Ext1"].ToString();
                    version = dtInver.Rows[0]["Version"].ToString();
                }
                bool isPD = false;
                if (string.IsNullOrEmpty(extInver) || extInver.Length != 8)
                {
                    isPD = true;
                }
                //有扩展日期
                else
                {
                    try
                    {
                        DateTime ditetimeExt = Convert.ToDateTime(extInver.Substring(0, 4) + "-" + extInver.Substring(4, 2) + "-" + extInver.Substring(6, 2));
                        if (outType.Equals("FATP"))
                        {
                            if (ditetimeExt >= Utils.GetSysDate().AddDays(-60))
                            {
                                MessageBox.Show("扩展有效期天数小于等于60天，不允许出货，请找OQC确认");
                                return;
                            }
                        }
                        else if (outType.Equals("Flex etc"))
                        {
                            if (ditetimeExt >= Utils.GetSysDate().AddDays(-30))
                            {
                                MessageBox.Show("扩展有效期天数小于等于30天，不允许出货，请找OQC确认");
                                return;
                            }
                        }
                        else
                        {
                            if (ditetimeExt >= Utils.GetSysDate())
                            {
                                isPD = false;
                            }
                        }
                    }
                    catch
                    {
                        MessageBox.Show("该库位有效期不是正确的日期格式!");
                        return;
                    }
                }
                if (isPD)
                {
                    var dtLiftTime = Bll_ProductOut.GetExpriTime(realPartNumber, realLocationSN);
                    if (dtLiftTime.Rows.Count > 0)
                    {
                        var lifeTime = Convert.ToInt16(dtLiftTime.Rows[0]["ShelfLifeTime"].ToString());
                        var diff = Convert.ToInt16(dtLiftTime.Rows[0]["Diff"].ToString());

                        if (outType.Equals("FATP"))
                        {
                            if (diff <= 60)
                            {
                                MessageBox.Show("管控有效期天数小于等于60天，不允许出货，请找OQC确认");
                                return;
                            }
                        }
                        else if (outType.Equals("Flex etc"))
                        {
                            if (diff <= 60)
                            {
                                MessageBox.Show("管控有效期天数小于等于30天，不允许出货，请找OQC确认");
                                return;
                            }
                        }
                        else
                        {
                            if (lifeTime <= 30 && diff <= 7)
                            {
                                MessageBox.Show("有效期不足7天，无法出库!!");
                                return;
                            }

                            if (lifeTime > 30 && diff <= 30)
                            {
                                MessageBox.Show("有效期不足30天，无法出库!!");
                                return;
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("该物料有效期已过，无法出库!!");
                        return;
                    }
                }
            }
            //判断出货数量
            var isCanAddQty = Bll_ProductOut.OutStockIsCanAddQty(cmb_Doc.Text, realPartNumber, qty);
            if (!isCanAddQty)
            {
                MessageBox.Show("物料号" + realPartNumber + "的出库数量" + qty + "不能大于计划数量!");
                //txt_Qty.Text = "";
                return;
            }

            bool isTrue = false;
            StringBuilder sb = new StringBuilder();
            // 循环所有可出库箱号，逐箱出库
            foreach (BoxInfo info in this.outBoxList)
            {
                if (doProductOutStockByBox(info.BoxNo, info.Qty, sb))
                {
                    isTrue = true;
                }
            }

            if (isTrue)
            {
                // 更新入库单出库状态
                Bll_ProductOut.UpdateBillNoOutStock(txt_BoxNo.Text);

                _RecomDt = Utils.NMS.sqlDBService.GetSuggestSN(lab_StorageSN.Text, cmb_Doc.Text);
                var Isend = false;
                sb.AppendLine("当前料号:" + recomPartNumber + " " + version);
                lab_msg.Text = sb.ToString() + GetBillInfoMsg(cmb_Doc.Text, out Isend);
                GetRecommend();
            }
            else
            {
                var Isend = false;
                sb.AppendLine("当前料号:" + recomPartNumber + " " + version);
                lab_msg.Text = sb.ToString() + GetBillInfoMsg(cmb_Doc.Text, out Isend);
            }

            isInStockBillNo = false;
        }

        /// <summary>
        /// 出库（箱单位）
        /// </summary>
        /// <param name="boxNo">箱号</param>
        /// <param name="qty">数量</param>
        /// <param name="sb">出库LOG</param>
        private bool doProductOutStockByBox(string boxNo, string qty, StringBuilder sb)
        {
            // 是否已冻结
            if (_BillType.Contains("返工出库单") == false)
            {
                DataTable dateHoldBox = Bll_ProductOut.GetHoldBox(boxNo);
                if (dateHoldBox != null && dateHoldBox.Rows.Count > 0)
                {
                    sb.AppendLine(boxNo + "已冻结，不能出库！");
                    return false;
                }
            }

            // 是否已扫描
            var isExit = Bll_ProductOut.IsExitBill(cmb_Doc.Text, boxNo);
            if (isExit)
            {
                sb.AppendLine(boxNo + "已扫描！");
                return false;
            }

            // 是否存在
            var dtBox = Bll_ProductOut.GetBoxInfo(txt_BoxNo.Text, boxNo);
            if (dtBox == null || dtBox.Rows.Count == 0)
            {
                sb.AppendLine(boxNo + "箱号信息不存在，请确认此箱物料号与出库单中物料号一致！");
                return false;
            }

            // 是否已被使用
            var realQty_Box = 0;
            if (!string.IsNullOrEmpty(dtBox.Rows[0]["RealQty"].ToString()))
            {
                realQty_Box = Convert.ToInt32(dtBox.Rows[0]["RealQty"]);
            }
            if (dtBox.Rows[0]["Status"].ToString().Equals("1") || realQty_Box == 0)
            {
                sb.AppendLine(boxNo + "已被使用，请选择其他箱！");
                return false;
            }

            // 箱号物料号是否一致
            if (!realPartNumber.Equals(dtBox.Rows[0]["PartNumber"].ToString()))
            {
                sb.AppendLine(boxNo + "箱号物料号不对，请选择其他箱！");
                return false;
            }

            var BoolBN = false;
            int iQty = Convert.ToInt32(Convert.ToDecimal(qty));
            if (dtBox != null && dtBox.Rows.Count > 0)
            {
                var PutawayQty = Convert.ToInt32(dtBox.Rows[0]["PutawayQty"]);
                if (PutawayQty < iQty)
                {
                    BoolBN = true;
                }
            }
            if (BoolBN)
            {
                sb.AppendLine(boxNo + "出库数量超过实际的数量！");
                return false;
            }

            bool isTrue = Utils.NMS.sqlDBService.ProductOutStock(cmb_Doc.Text, boxNo, iQty, realLocationSN, realPartNumber, Utils.uContext.UserNamek__BackingField);
            if (isTrue)
            {
                sb.AppendLine(boxNo + "出库成功！");
            }
            else
            {
                sb.AppendLine(boxNo + "出库失败，请检查箱号与库位是否一致,或此库位是否有足够的成品！");
            }
            return isTrue;
        }
    }
}